/* eslint-disable max-lines */
import React from 'react';
import * as api from './api';
import routes from './routes';
import * as Enum from '../Enum';
import styles from './style.css';
import PropTypes from 'prop-types';
import * as actions from './actions';
import MultipleSelect from './MultipleSelect';
import ItemTypeSelect from './ItemTypeSelect';
import InputAmount from '../common/InputAmount';
import InputPercent from '../common/InputPercent';
import WrappedSelect from '../common/WrappedSelect';
import TextInput from 'Shared/components/TextInput';
import TagSelect from 'Shared/components/TagSelect';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, formatMessage, language} from './intl';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedInputNumber from '../common/WrappedInputNumber';
import {getProductCategories} from '../TechnologyActivity/api';
import {Spin, Card, Button, Row, Col, Form, Input, Table, Popconfirm} from 'antd';
import {conventEnumValueToString, uuid} from '../utils';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
const marketingActivityTargetType = Enum.marketingActivityTargetType.toList(language);
class NewPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {
            mainItem: [],
            marketingProduct: []
        },
        isValidate: false,
        activityItems: [],
        activityTarget: [],
        resultDetails: [],
        productCategory: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        getProductCategories({
            type: 2,
            isAll: true,
            pageIndex: 0,
            pageSize: 100}).then(res => {
            this.setState({
                productCategory: res.data.content
            });
        });
        if(this.props.id) {
            this.setState({isFetching: true});
            api.getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: {
                                ...res.data,
                                mainItem: res.data.mainItem ? res.data.mainItem : []
                            },
                            activityItems: res.data.activityItems.map(item => ({
                                itemtype: [
                                    item.parentMarketingActivityItemCategoryId,
                                    item.marketingActivityItemCategoryId
                                ],
                                ...item
                            })),
                            activityTarget: res.data.activityTarget,
                            resultDetails: res.data.resultDetails
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
        } else {
            const data = [];
            // eslint-disable-next-line array-callback-return
            marketingActivityTargetType.map(item => {
                data.push({
                    id: uuid(),
                    type: item.value,
                    lastData: 1,
                    estimateData: 1,
                    proportion: 0.1
                });
            });
            this.setState({
                activityTarget: data
            });
        }
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    // eslint-disable-next-line react/sort-comp
    onClickAddDetl = () => {
        const activityItems = this.state.activityItems;
        this.setState({
            activityItems: [
                ...activityItems,
                {
                    id: uuid(),
                    itemtype: [],
                    marketingActivityItemCategoryId: '',
                    marketingActivityItemCategoryName: '',
                    parentMarketingActivityItemCategoryId: '',
                    parentMarketingActivityItemCategoryName: '',
                    item: '',
                    amount: 1,
                    remark: ''
                }
            ]
        });
    }
    targetcolumsChange = (value, name, id) => {
        const activityTarget = this.state.activityTarget.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value
                });
            return d;
        });
        this.setState({
            activityTarget,
            hasOperat: true
        });
    }
    columsChange = (value, name, id) => {
        const activityItems = this.state.activityItems.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value
                });
            return d;
        });
        this.setState({
            activityItems,
            hasOperat: true
        });
    }
    onDeselect = value => {
        const {data} = this.state;
        const parts = data.marketingProduct || [];
        this.setState({
            data: Object.assign({}, this.state.data, {
                marketingProduct: parts.filter(v => v.productCategoryId !== value.key)
            }),
            hasOperat: true
        });
    }
    onSelectProduct = conditions => {
        const {data} = this.state;
        const parts = data.marketingProduct || [];
        conditions.forEach(d => {
            const index = parts.findIndex(v => v.productCategoryId === d.key);
            if(index === -1)
                parts.push({
                    productCategoryId: d.key,
                    productCategoryCode: d.label,
                    productCategoryName: d.label
                });
        });
        this.setState({
            data: Object.assign({}, this.state.data, {
                marketingProduct: [...parts]
            }),
            hasOperat: true
        });
    }
    onSubmit = () => {
        const {initEnum} = this.props;
        const {data, activityTarget, activityItems} = this.state;
        const brandId = initEnum && initEnum.brands.length > 0
            ? initEnum.brands[0].value : data.brandId;
        const currency = this.props.id
            ? data.currency : initEnum.currency;
        const isValid = newOrUpdateOrderValidator(data, brandId, 1, activityTarget, activityItems);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        this.setState({isFetching: true});
        this.props.onSubmit(data, brandId, currency, activityTarget, activityItems).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({isFetching: false});
        });
    };
    render() {
        const {initEnum} = this.props;
        const {data, isFetching, isValidate, activityTarget, activityItems, productCategory} = this.state;
        const validateBrands = !data.brandId && isValidate ? 'error' : null;
        const validateTheme = !data.theme && isValidate ? 'error' : null;
        const validateBackground = !data.background && isValidate ? 'error' : null;
        const validatestatDate = !data.statDate && isValidate ? 'error' : null;
        const validateendDate = !data.endDate && isValidate ? 'error' : null;
        const validateMainItem = !data.mainItem && isValidate ? 'error' : null;
        const validateMainItemRemark = !data.mainItemRemark && isValidate ? 'error' : null;
        const validateCustomerQTY = !data.customerQTY && isValidate ? 'error' : null;
        const vehicleWarranty = !data.vehicleWarranty && isValidate ? 'error' : null;
        const validateScope = !data.scope && isValidate ? 'error' : null;
        const validateContent = !data.content && isValidate ? 'error' : null;
        const validateMarketingProduct = !data.marketingProduct && isValidate ? 'error' : null;
        const targetcolums = [{
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.type',
                    defaultMessage: '分类'
                })}</span>,
            dataIndex: 'type',
            render: text => conventEnumValueToString(Enum.marketingActivityTargetType, text)
        }, {
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.lastData',
                    defaultMessage: '上次数据'
                })}</span>,
            dataIndex: 'lastData',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <WrappedInputNumber
                            name="lastData"
                            value={text}
                            onBlur={v => this.targetcolumsChange(v, 'lastData', record.id)} />
                    </Form.Item>
                );
            }
        }, {
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.estimateData',
                    defaultMessage: '预计数据'
                })}
            </span>,
            dataIndex: 'estimateData',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <WrappedInputNumber
                            name="estimateData"
                            value={text}
                            onBlur={v => this.targetcolumsChange(v, 'estimateData', record.id)} />
                    </Form.Item>
                );
            }
        }, {
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.proportion',
                    defaultMessage: '增幅比例'
                })}
            </span>,
            dataIndex: 'proportion',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <InputPercent
                            name="proportion"
                            value={text}
                            onBlur={v => this.targetcolumsChange(v, 'proportion', record.id)} />
                    </Form.Item>
                );
            }
        }, {
            title: activityTarget && activityTarget.length > 0
                ? (<Popconfirm placement="topRight" title={formatMessage({
                    id: 'newPanel.column.allDelete',
                    defaultMessage: '是否确认全部删除？'
                })} onConfirm={() => this.setState({activityTarget: []})} >
                    <a>{formatMessage({
                        id: 'newPanel.column.empty',
                        defaultMessage: '清空'
                    })}</a>
                </Popconfirm>)
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={e => {
                const id = e.target.dataset.id;
                const tmp = this.state.activityTarget.filter(d => d.id !== id);
                this.setState({
                    activityTarget: [...tmp],
                    hasOperat: true
                });
            }}>{formatMessage({
                    id: 'newPanel.column.delete',
                    defaultMessage: '删除'
                })}</a>
        }];
        const colums = [{
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.marketingActivityItemCategoryId',
                    defaultMessage: '项目类型'
                })}</span>,
            dataIndex: 'itemtype',
            render: (text, record) => {
                const validate = !text || text.length === 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <ItemTypeSelect
                            name="itemtype"
                            defaultOption={{...record}}
                            value={text}
                            onChange={v => this.columsChange(v, 'itemtype', record.id)}
                            changeOnSelect={true} />
                    </Form.Item>
                );
            }
        }, {
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.item',
                    defaultMessage: '项目'
                })}</span>,
            dataIndex: 'item',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <TextInput
                            name="item"
                            value={text}
                            onBlur={v => this.columsChange(v, 'item', record.id)} />
                    </Form.Item>
                );
            }
        }, {
            title: <span className="ant-form-item-required">
                {formatMessage({
                    id: 'detailPanel.column.amount',
                    defaultMessage: '费用'
                })}</span>,
            dataIndex: 'amount',
            render: (text, record) => {
                const validate = (!text || text === undefined) && text !== 0 ? {validateStatus: 'error'} : null;
                return (
                    <Form.Item {...validate}>
                        <InputAmount
                            name="amount"
                            value={text}
                            onBlur={v => this.columsChange(v, 'amount', record.id)} />
                    </Form.Item>
                );
            }
        }, {
            title: formatMessage({
                id: 'detailPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
            render: (text, record) => (
                <Form.Item>
                    <TextInput
                        name="remark"
                        value={text}
                        onBlur={v => this.columsChange(v, 'remark', record.id)} />
                </Form.Item>
            )
        }];
        return (
            <div className="form-standard">
                <Spin spinning={isFetching}>
                    <Card title={formatMessage({
                        id: 'newPanel.card.title',
                        defaultMessage: '活动申报信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.form.code',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {this.props.id
                                            ? data.code
                                            : <Input placeholder={formatMessage({
                                                id: 'newPanel.form.notGenerate',
                                                defaultMessage: '尚未生成'
                                            })}
                                            disabled />}
                                    </Form.Item>
                                </Col>
                                {initEnum.brands && initEnum.brands.length > 1 &&
                                 <Col {...FORM_OPTIONS.col}>
                                     <Form.Item label={formatMessage({
                                         id: 'newPanel.form.brandName',
                                         defaultMessage: '品牌'
                                     })} {...FORM_OPTIONS.item} validateStatus={validateBrands} required>
                                         {this.props.id
                                             ? `${data.brandCode}(${data.brandName})`
                                             : <WrappedSelect
                                                 allowClear
                                                 name="brandId"
                                                 value={data.brandId}
                                                 options={initEnum.brands}
                                                 onChange={this.handleFilterChange}/>}
                                     </Form.Item>
                                 </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.form.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item} required>
                                        {conventEnumValueToString(Enum.currency, this.props.id
                                            ? data.currency : initEnum.currency)}
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.form.theme',
                                        defaultMessage: '主题'
                                    })}
                                    {...FORM_OPTIONS.item} validateStatus={validateTheme} required>
                                        <TextInput
                                            name="theme"
                                            value={data.theme}
                                            onBlur={this.handleFilterChange}/>
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item label={formatMessage({
                                        id: 'newPanel.form.background',
                                        defaultMessage: '背景'
                                    })}
                                    {...FORM_OPTIONS.item} validateStatus={validateBackground} required>
                                        <TextInput
                                            name="background"
                                            value={data.background}
                                            onBlur={this.handleFilterChange}/>
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.statDate',
                                            defaultMessage: '开始日期'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validatestatDate} required>
                                        <WrappedDatePicker
                                            name="statDate"
                                            value={data.statDate}
                                            onChange={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.endDate',
                                            defaultMessage: '结算日期'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateendDate} required>
                                        <WrappedDatePicker
                                            name="endDate"
                                            value={data.endDate}
                                            onChange={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.customerQTY',
                                            defaultMessage: '目标用户量'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateCustomerQTY} required>
                                        <WrappedInputNumber
                                            name="customerQTY"
                                            value={data.customerQTY}
                                            onBlur={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.vehicleWarranty',
                                            defaultMessage: '车辆政策'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={vehicleWarranty} required>
                                        <TextInput
                                            name="vehicleWarranty"
                                            value={data.vehicleWarranty}
                                            onBlur={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.scope',
                                            defaultMessage: '营销目标'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateScope} required>
                                        <TextInput
                                            name="scope"
                                            value={data.scope}
                                            onBlur={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.productCategoryCode',
                                            defaultMessage: '营销车型'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateMarketingProduct} required>
                                        <MultipleSelect
                                            name="marketingProduct"
                                            dataOptions={productCategory}
                                            onDeselect={this.onDeselect}
                                            value={data.marketingProduct.map(item => item.productCategoryId)}
                                            onBlur={this.onSelectProduct} />
                                    </Form.Item>
                                </Col>
                                {data.mainItem && data.mainItem.indexOf(6) !== -1 &&
                                <Col {...FORM_OPTIONS.col}>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.mainItemRemark',
                                            defaultMessage: '主项目备注'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={data.mainItem && data.mainItem.indexOf(6) !== -1 && validateMainItemRemark}
                                        required={data.mainItem && data.mainItem.indexOf(6) !== -1}>
                                        <TextInput
                                            name="mainItemRemark"
                                            value={data.mainItemRemark}
                                            onBlur={this.handleFilterChange}/>
                                    </Form.Item>
                                </Col>}
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.mainItem',
                                            defaultMessage: '主项目'
                                        })}
                                        {...FORM_ROW_OPTIONS.item} validateStatus={validateMainItem} required>
                                        <TagSelect
                                            name="mainItem"
                                            value={data.mainItem}
                                            options={Enum.marketingStatus.toList(language)}
                                            onChange={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <Form.Item
                                        label={formatMessage({
                                            id: 'newPanel.form.content',
                                            defaultMessage: '营销内容'
                                        })}
                                        {...FORM_ROW_OPTIONS.item} validateStatus={validateContent} required>
                                        <TextInput
                                            type="textarea"
                                            name="content" value={data.content}
                                            onBlur={this.handleFilterChange} />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.table.activityTarget',
                        defaultMessage: '活动预期清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={targetcolums}
                            rowKey="id"
                            pagination={false}
                            dataSource={activityTarget}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'newPanel.table.activityItems',
                        defaultMessage: '活动项目清单'
                    })}>
                        <Button
                            type="dashed"
                            icon="plus"
                            block
                            className={styles.plusBtn}
                            onClick={this.onClickAddDetl}>
                            {formatMessage({
                                id: 'newPanel.operation.new',
                                defaultMessage: '新增'
                            })}
                        </Button>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={activityItems}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={isFetching}>
                            {formatMessage({
                                id: 'newPanel.btn.submit',
                                defaultMessage: '提交'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.props.onCancel}>{formatMessage({
                        id: 'newPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const currency = initData.currency ? initData.currency : 1;
        const isDealerUser = initData.isDealerUser;
        const dealerService = initData.dealerService;
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            dealerService,
            isDealerUser,
            brands,
            currency
        };
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    initEnum: getInitData(state),
    permissions: getPermissions(state)
});

const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, brandId, currency, activityTarget, activityItems) =>
        dispatch(actions.onSubmit(data, brandId, currency, activityTarget, activityItems)),
    successReturn: () => {
        dispatch(actions.tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
